package com.duoduo.双指针;

/**
 * @program: algorithm
 * @description: 反转字符串中的单词 III
 * 给定一个字符串 s ，你需要反转字符串中每个单词的字符顺序，同时仍保留空格和单词的初始顺序。
 * 输入：s = "Let's take LeetCode contest"
 * 输出："s'teL ekat edoCteeL tsetnoc"
 * @author: chaidl  ！
 * @create: 2022-03-16 19:44
 */
public class 反转字符串中的单词III {
    public String reverseWords(String s) {
        char[] chars = s.toCharArray();
        int n=chars.length;
        int left=0,right = 0;
        while (right<n) {
            if (chars[right]!=' '){
                right++;
            }else {
                swap(chars, left, right-1);
                left=right+1;
                right+=1;
            }
        }
        swap(chars,left,right-1);
        return new String(chars);
    }

    private void swap(char[] chars, int left, int right) {
        while (left <=right){
            char tmp=chars[left];
            chars[left] = chars[right];
            chars[right] = tmp;
            left++;
            right--;
        }
    }
}
